package cn.edu.zafu.bigdata.LiJuan;

public class SynchronizeDemo {
    public static void main(String[] args) throws Exception {
       /* Thread t1=new AddThread();
        Thread t2=new DecThread();
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(Counter.count);*/

        var ts=new Thread[]{new AddStudentThread(),new DecStudentThread(),new AddTeacherThread(),new DecTeacherThread()};
        for(var t : ts){
            t.start();
        }
        for(var t : ts){
            t.join();
        }
        System.out.println(Counter.studentCounter);
        System.out.println(Counter.teacherCounter);
    }
}
//定义计数器类
class Counter{
    public static final Object lock1=new Object();
    public static final Object lock2=new Object();
    //public static int count=0;
    public static int studentCounter=0;
    public static int teacherCounter=0;

}

/*class AddThread extends Thread{
    //重写run方法
    public void run(){
       // Counter c=new Counter();
        for (int i = 0; i < 10000; i++) {
            synchronized(Counter.lock) {
                Counter.count++;
            }
        }
    }
}
class DecThread extends Thread{
    //重写run方法
    public void run() {
        //Counter c=new Counter();
        for (int i = 0; i < 10000; i++) {
            synchronized (Counter.lock) {
                Counter.count--;
            }
        }
    }*/




class AddStudentThread extends Thread{
    public void run(){
        for (int i = 0; i < 10000; i++) {
            synchronized(Counter.lock1){
                Counter.studentCounter+=1;
            }
        }
    }
}
class DecStudentThread extends Thread{
    public void run(){
        for (int i = 0; i < 10000; i++) {
            synchronized(Counter.lock1){
                Counter.studentCounter-=1;
            }
        }
    }
}
class AddTeacherThread extends Thread{
    public void run(){
        for (int i = 0; i < 10000; i++) {
            synchronized (Counter.lock2){
                Counter.teacherCounter+=1;
            }

        }
    }
}
class DecTeacherThread extends Thread{
    public void run(){
        for (int i = 0; i < 10000; i++) {
            synchronized(Counter.lock2){
                Counter.teacherCounter-=1;
            }
        }
    }
}




